package instant;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTopic;

import javax.jms.*;
import javax.naming.InitialContext;
import java.io.BufferedReader;

/**
 * Created with Intel IDEA.
 * 一个聊天的类
 *
 * @Auther: gjt
 * @Date: 2024/10/27 15:43
 */

public class Chat implements MessageListener {
    private TopicSession pubSession;
    private TopicPublisher publisher;
    private TopicConnection connection;

    private String userName;


    private static String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static String BROKER = ActiveMQConnection.DEFAULT_BROKER_URL;

    /**
     *  用于初始化Chat 的构造函数
     */
    public Chat(String topicFactory, String topicName, String userName) throws Exception {

        // 使用jndi.properties 文件获取一个JNDI连接
        InitialContext ctx = new InitialContext();

        TopicConnectionFactory conFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER);

//        // 查找一个JMS连接工厂并创建连接
//        TopicConnectionFactory conFactory = (TopicConnectionFactory) ctx.lookup(topicFactory);

        TopicConnection connection = conFactory.createTopicConnection();

        // 创建两个session 会话对象
        TopicSession pubSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        TopicSession subSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        // 查找一个JMS主题对象
//        Topic chatTopic = (Topic)ctx.lookup(topicName);
        ActiveMQTopic chatTopic = new ActiveMQTopic(topicName);

        // 创建一个JMS发布者和订阅者。附件的参数表示消息选择器（null）和 noLocal 标记的一个真值，表明这个发布者生产的消息不应该被它自己所消费。
        TopicPublisher publisher = pubSession.createPublisher(chatTopic);
        TopicSubscriber subscriber = subSession.createSubscriber(chatTopic, null, true);

        // 设置一个消息监听器
        subscriber.setMessageListener(this);

        //初始化chat 应用程序变量
        this.connection = connection;
        this.publisher = publisher;
        this.pubSession = pubSession;
        this.userName = userName;

        // 启动JMS 连接； 允许传送消息
        connection.start();
    }

    /**
     * 接收来自TopicSubscriber 的消息
     */
    @Override
    public void onMessage(Message message) {
        try {
            int jmsDeliveryMode = message.getJMSDeliveryMode();
            int persistent = DeliveryMode.PERSISTENT;
            TextMessage textMessage = (TextMessage) message;


            String jmsCorrelationID = message.getJMSCorrelationID();
            System.out.println(textMessage.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }


    /**
     *  使用发布者创建并发送消息
     */
    protected void writeMessage(String text) throws JMSException {
        TextMessage message = pubSession.createTextMessage();
        message.setText(userName + ": " + text);
        publisher.publish(message);
    }


    /**
     * 关闭JMS 连接
     */
    public void close() throws JMSException {
        connection.close();
    }

    public static void main(String[] args) {
        try{
//            if(args.length != 3){
//                System.out.println("Factory.Topic.Or username missing");
//            }

            Chat chat = new Chat(args[0],args[1],args[2] );

            // 从命令行中读取
            BufferedReader commands = new BufferedReader(new java.io.InputStreamReader(System.in));
            while(true){
                String line = commands.readLine();
                if(line.toUpperCase().startsWith("EXIT")){
                    chat.close();
                    System.exit(0);
                }else {
                    chat.writeMessage(line);
                }
                chat.writeMessage(line);
            }
        }catch (Exception e){
            System.out.println(e);
        }
    }
}
